//https://juejin.cn/post/7041515221625602055
// 1、通过异步函数和Promise.race
const request = (url, time) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(`任务${url}完成`)
        }, time || 1000);
    })
}



async function p_limit(limitNum, urls) {
    let pool = [] //并发池
    let max = limitNum; //最大并发数

    for (let i = 0; i < urls.length; i++) {
        const url = urls[i];
        const task = request(url, times[i])
        //推入并发池

        task.then(res => {
            // console.log("输出结果==>", res);
            pool.splice(pool.indexOf(task, 1))
        })
        pool.push(task)
        console.log("pool", pool.length);
        if (pool.length === max) {
            //利用Promise.race 来获取并发池中最快完成的任务
            //结合await 当有任务完成，才让程序继续进行
            let res = await Promise.race(pool)
            console.log("===>", res);
        }
    }
}
// let urls = ['bytedance.com', 'tencent.com', 'alibaba.com', 'microsoft.com', 'apple.com', 'hulu.com', 'amazon.com'] // 请求地址
// let times = [600, 1500, 1600, 2000, 5000, 1500, 1000] // 请求地址
// p_limit(3, urls)


var delay = (time) => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('1')
        }, time);
    })
}

//for 循环 和await
async function afn(params) {
    for (let i = 0; i < 6; i++) {
        console.log("打印", i);
        if (i == 2) {
            await delay(10000)
        }
    }
}

// afn()


/**
 * 2、使用递归的方法
 */

function p_limit_digui(limitNum, urls) {
    const max = limitNum;
    const results = new Array(urls.length).fill(false)
    let index = 0

    return new Promise((resolve, reject) => {
        while (index < max) {
            next()
        }
        function next() {
            const currentIndex = index++
            const curUrl = urls[currentIndex]
            //出口
            if (currentIndex >= urls.length) {
                console.log("最终结果", results);
                return resolve(results)
            }
            // console.log('结果==》', currentIndex,);
            //发起请求
            request(curUrl, times[currentIndex]).then(res => {
                console.log("打印当前结果", currentIndex, res);
                results[currentIndex] = res
                // 请求没有全部完成, 就递归
                if (currentIndex < urls.length) {
                    next()
                }
            }).catch(err => {
                console.log("错误", err);
            })
        }
    })


}

let urls = ['bytedance.com', 'tencent.com', 'alibaba.com', 'microsoft.com',] // 请求地址
let times = [1600, 5500, 600, 2000] // 请求地址

p_limit_digui(2, urls)
